<template>
	<div style="border: 1px solid #ccc;">
		<Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" :mode="mode" />
		<Editor style="height: 500px; overflow-y: hidden;" :value="value" :defaultConfig="editorConfig" :mode="mode"
			@input="$emit('input', $event)" @onCreated="onCreated" />
	</div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
// 处理WangEditor的初始化问题
import { Boot } from '@wangeditor/editor';
// editor为空获取value值存在"<p><br></p>"，在表单中无法校验，借助于插件解决
function withEmptyHtml(editor) {
	const { getHtml } = editor
	const newEditor = editor
	newEditor.getHtml = () => {
		if (newEditor.isEmpty()) {
			return ''
		}
		return getHtml()
	}
	return newEditor
}
// 注册插件
Boot.registerPlugin(withEmptyHtml);

export default {
	props: {
		value: {
			type: String,
			default: '',
		},
		server: {
			type: String,
			default: `${process.env.VUE_APP_SERVER}/upload/editor/`,
		},
		headers: {
			type: Object,
			default: () => ({
				Authorization: `Bearer ${sessionStorage.access_token}`,
			}),
		},
		fieldName: {
			type: String,
			default: '',
		},
	},
	components: { Editor, Toolbar },
	data() {
		return {
			editor: null,
			toolbarConfig: {},
			editorConfig: {
				placeholder: '请输入内容...',
				MENU_CONF: {
					uploadImage: {
						server: this.server,
						headers: this.headers,
						fieldName: this.fieldName,
					}
				}
			},
			mode: 'default', // or 'simple' 简化版
		}
	},
	methods: {
		onCreated(editor) {
			this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
		},
	},
	beforeDestroy() {
		const editor = this.editor
		if (editor == null) return
		editor.destroy() // 组件销毁时，及时销毁编辑器
	}
}
</script>

<style></style>
